<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :xs="15" :sm="18" :md="19" :lg="20" :xl="20">
        <!--工具栏-->
        <div class="head-container">
          <div class="center_f" v-show="isShow">
            <!-- 搜索 -->
            <div class="box_si">
              <el-input
                placeholder="请输入姓名"
                v-model="input"
                @keyup.enter.native="queryList()"
                clearable>
              </el-input>
            </div>
            <!--日期-->
            <div class="block">
              <el-date-picker
                v-model="RolesDate"
                type="daterange"
                align="right"
                unlink-panels
                range-separator=":"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions">
              </el-date-picker>
            </div>
            <el-button type="success" icon="el-icon-search" size="small" class="box_ss" @click="queryList()">搜索</el-button>
            <el-button type="warning" icon="el-icon-refresh" size="small" @click="resetForm()">重置</el-button>
          </div>
          <!--          增删改-->
          <div class="list_box_c">
              <span class="list_box_left">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="addMembers()">新增</el-button>
                <el-button type="danger" disabled size="small" icon="el-icon-delete">删除</el-button>
                <el-button type="warning" size="small" icon="el-icon-download">导出</el-button>
              </span>
            <div class="list_box_right">
              <el-button icon="el-icon-search" size="small" @click="changeIsShow()"></el-button>
              <el-button icon="el-icon-refresh" size="small" @click="refresh()"></el-button>
            </div>
          </div>
          <!--          新增用户-->
          <el-dialog title="新增角色" :visible.sync="isAddMembers" width="30%" style="font-weight: bold">
            <el-form :model="addForm" :rules="rules" ref="addForm" class="demo-ruleForm">
              <el-form-item label="角色名称" prop="role_name">
                <div class="center-box" style="display: flex">
                  <el-input v-model="addForm.role_name"></el-input>
                </div>
              </el-form-item>
              <el-form-item label="角色级别" prop="role_level">
                <el-input-number v-model="addForm.role_level" controls-position="right" :min="0" :max="3"></el-input-number>
              </el-form-item>
              <el-form-item label="描述信息" prop="role_info">
                <el-input type="textarea" :rows="5" v-model="addForm.role_info"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="closeDialog()">取 消</el-button>
              <el-button type="primary" @click="submitForm()">确 定</el-button>
            </span>
          </el-dialog>
          <!--            编辑用户-->
          <el-dialog title="新增角色" :visible.sync="centerDialogVisible" width="30%" style="font-weight: bold">
            <el-form :model="updateForm" :rules="rules" ref="updateForm" class="demo-ruleForm">
              <el-form-item label="角色名称" prop="role_name">
                <div class="center-box" style="display: flex">
                  <el-input v-model="updateForm.role_name"></el-input>
                </div>
              </el-form-item>
              <el-form-item label="角色级别" prop="role_level">
                <el-input-number v-model="updateForm.role_level" controls-position="right" :min="0" :max="3"></el-input-number>
              </el-form-item>
              <el-form-item label="描述信息" prop="role_info">
                <el-input type="textarea" :rows="5" v-model="updateForm.role_info"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="closeDialog()">取 消</el-button>
              <el-button type="primary" @click="sumbitEditRow()">确 定</el-button>
            </span>
          </el-dialog>
        </div>
      </el-col>
    </el-row>
    <div class="content">
      <div class="center-left">
        <div class="content-top">
          <h3>角色列表</h3>
        </div>
        <div class="content-bottom">
          <el-table
            ref="singleTable"
            :data="tableData"
            class="center-con"
            @row-click="queryRoleMenu"
            style="width: 100%">
            <el-table-column
              label=""
              width="55"
              align="center">
              <template slot-scope="scope">
                <el-radio-group v-model="tempRadio">
                  <el-radio :label="scope.row.role_id" @click.native.prevent="clickitem(scope.row.role_id)">{{''}}</el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column
              prop="role_name"
              label="名称">
            </el-table-column>
            <el-table-column
              prop="role_level"
              label="角色级别">
            </el-table-column>
            <el-table-column
              prop="role_info"
              label="描述">
            </el-table-column>
            <el-table-column
              prop="create_time"
              label="创建日期">
            </el-table-column>
            <el-table-column
              prop="address"
              label="操作"
              width="150px">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" circle @click="modifyData(scope.$index, scope.row)"></el-button>
                <el-button class="btn_x" size="medium" type="text" icon="el-icon-delete" @click="removeRoles(scope.row.role_id)"></el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <pagination
            :total="totalCount"
            :pageNum="pageNum"
            :pageSize="pageSize"
            @pageChange="pageChange"
          />
        </div>
      </div>
      <div class="center-right">
        <div class="content-top">
          <h3>菜单分配</h3>
          <el-button type="primary" size="mini" icon="el-icon-check" @click="updateMenu()">保存</el-button>
        </div>
        <div class="content-bottom">
          <el-tree
            ref="tree"
            :data="queryData"
            show-checkbox
            node-key="menu_id"
            :props="defaultProps"
            :check-strictly="true"
            :default-checked-keys="checkedRole"
            accordion>
          </el-tree>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import pagination from '../../../pagination/pagination'
  export default {
    inject: ['reload'],
    components: { pagination },
    data () {
      return {
        // 控制修改用户对话框的显示与隐藏
        centerDialogVisible: false,
        // 控制添加用户对话框的显示与隐藏
        isAddMembers: false,
        // 搜索的绑定
        input: '',
        e: '',
        // 当前页码
        pageNum: 0,
        // 默认每页数据量
        pageSize: 5,
        // 共有多少条数据
        totalCount: 0,
        // 表格
        tableData: [],
        role_id: '',
        // 树形列表
        queryData: [],
        checkedRole: [],
        // isCheck: false,
        defaultProps: {
          children: 'childMenus',
          label: 'menu_name'
        },
        // 新增的参数为空
        addForm: {},
        // 修改的参数
        updateForm: {},
        // 表单的校验
        rules: {
          role_name: [
            {min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur'}
          ]
        },
        // 搜索框显示或隐藏
        isShow: true,
        istrue: '',
        isvalidate: '',
        sysUser: '',
        tempRadio: '',
        // 日期
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        RolesDate: ''
      }
    },
    /**
     * @author hpx
     * @date 2021/9/24 8:58
     * 搜索名称时按回车键
     */
    created() {
      this.queryMeun()
      const that = this
      document.addEventListener('keydown', that.queryList())
    },
    methods: {
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 点击新增弹框打开
       */
      addMembers() {
        this.isAddMembers = true
        this.addForm = {// 再次点击新增时处于清空状态
          role_name: '',
          role_level: 0,
          role_info: ''
        }
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 点击编辑时弹框打开
       */
      modifyData(index, row) {
        this.centerDialogVisible = true
        this.updateForm = Object.assign({}, row) // 重置对象
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 重置搜索框，日期
       */
      resetForm: function () {
        this.input = ''
        this.RolesDate = ''
        this.queryList()
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 分页
       */
      pageChange(page) {
        this.pageSize = page.pageSize
        this.pageNum = page.currentPage
        this.queryList()// 查询列表方法
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 查询所有菜单分配
       */
      queryMeun() {
        this.$axios.get('/queryAllMenu').then(resp => {
          if (resp && resp.status === 200) {
            this.queryData = resp.data
          }
        })
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 查询菜单id分配
       */
      queryRoleMenu(row) {
        this.role_id = row.role_id
        this.$axios.get('/querySysMenuByRole', {
          params: {
            role_id: this.role_id // 获取表格一行里面的数据，拿到里面的id
          }
        }).then(resp => {
          if (this.tempRadio !== '') {
            this.checkedRole = []
            this.$refs.tree.setCheckedKeys(this.checkedRole)
            for (let i = 0; i < resp.data.length; i++) {
              this.checkedRole.push(resp.data[i].menu_id)
              this.$refs.tree.setCheckedKeys(this.checkedRole)
            }
          } else {
            this.$refs.tree.setCheckedKeys([])
          }
        })
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 查询，搜索数据
       * if判断搜索框，日期为空时返回空字符串
       */
      queryList() {
        // 判断搜索框，日期框为空时，返回空字符串
        if (this.input == null) {
          return this.input == ""
        }
        if (this.RolesDate == "" || this.RolesDate == null) {
          this.RolesDate = ["", ""]
        }
        this.$axios.get('/queryRolesList', {
          params: {
            role_name: this.input,
            begindate: this.RolesDate[0],
            enddate: this.RolesDate[1],
            pageSize: this.pageSize,
            pageNum: this.pageNum
          }
        }).then(resp => {
          if (resp && resp.status === 200) {
            this.tableData = resp.data.pagelist
            this.totalCount = resp.data.totalsize
          }
        })
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 修改菜单分配并保存
       */
      updateMenu() {
        const updateNode = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
        const param = {
          role_id: this.role_id,
          menu_id: updateNode
        }
        this.$axios.post('/updateRoleMenu', param).then(resp => {
          if (resp.data == '0') {
            this.$confirm('保存失败', '提示', {
              type: 'warning'
            })
          } else if (resp.data == '1') {
            this.$confirm('保存成功', '提示', {
              type: 'warning'
            })
          }
          this.reload()
        })
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 保存并提交新增数据
       */
      submitForm() {
        if (this.addForm.role_name === '' || this.addForm.role_info === '') { // 非空校验
          this.$confirm('请输入完整内容?', '提示', {
            type: 'warning'
          })
        } else {
          this.$axios
            .post('/addRoles', this.addForm).then(resp => {
            this.istrue = resp.data
            if (this.istrue == '0') {
              this.$confirm('数据格式不规范?', '提示', {
                type: 'warning'
              })
            } else if (this.istrue == '1') {
              this.isAddMembers = false
            }
          })
        }
        setTimeout(() => {
          this.queryList()
        }, 200)
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 保存并提交修改数据
       */
      sumbitEditRow() {
        if (this.updateForm.role_name === '' || this.updateForm.role_info === '') {
          this.$confirm('请输入完整内容?', '提示', {
            type: 'warning'
          })
        }else {
          this.$axios
            .post('/updateRoles', this.updateForm).then(resp => {
            this.sysUser = resp.data.sysUser
            this.isvalidate = resp.data.isvalidate
            if (this.isvalidate == '0') {
              this.$confirm('数据格式不规范?', '提示', {
                type: 'warning'
              })
            } else if (this.isvalidate == '1') {
              this.centerDialogVisible = false
            }
          })
          setTimeout(() => {
            this.queryList()
          }, 200)
        }
      },
      /**
       * @author hpx
       * @date 2021/9/24 14:01
       * 删除数据
       */
      removeRoles(id) {
        this.$confirm('此操作将永久删除该文件?', '提示', {
          type: 'warning'
        }).then(() => {
          this.$axios
            .post('/deleteRoles', {
              role_id: id
            }).then(resp => {
            if (resp && resp.status === 200) {
              this.queryList()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 再次点击单选框时取消选中
       */
      clickitem(e) {
        e === this.tempRadio ? this.tempRadio = '' : this.tempRadio = e // 如果
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 关闭弹框
       */
      closeDialog() {
        this.centerDialogVisible = false
        this.isAddMembers = false
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 搜索框显示隐藏
       */
      changeIsShow() {
        this.isShow = !this.isShow
      },
      /**
       * @author hpx
       * @date 2021/9/24 8:58
       * 刷新表格
       */
      refresh() {
        this.reload()
      }
    }
  }
</script>
<style scoped>
  .el-col-lg-20 {
    width: 100%;
  }
  .center-con /deep/ thead th:first-child .el-checkbox{
    visibility: hidden;
  }
  .content{
    width: auto;
  }
  .center-left,.center-right{
    width: 68%;
    border-radius: 4px;
    border: 1px solid #e6ebf5;
    float: left;
  }
  .center-right{
    width: 30%;
    height: auto;
    /*margin-left: 20px;*/
    float: right;
  }
  .el-button--mini, .el-button--mini.is-round {
    padding: 7px;
    float: right;
  }
  .content-top{
    border-bottom: 1px solid #e6ebf5;
    padding: 15px;
    font-size: 14px;
  }
  .content-top h3{
    display: inline;
  }
  .content-bottom{
    padding: 20px;
  }
  .el-textarea {
    position: relative;
    display: inline-block;
    width: 85%;
    vertical-align: bottom;
    font-size: 14px;
  }
  .btn_x{
    display: inline-block;
    width: 40px;
    height: 40px;
    background: #F56C6C;
    border-radius: 50%;
    margin-left: 10px;
    color: white;
  }
</style>
